<template>
  <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'" draggable @before-ok="save" @close="reset">
    <fieldset>
      <legend>基础信息</legend>
      <GiForm ref="formRef" v-model="form" :columns="columns" />
    </fieldset>
    <fieldset>
      <legend>规则</legend>
      <a-space direction="vertical" fill>
        <p><Icon-question-circle-fill />周期填入最大即可，例如2年代表超过2年，5年代表超过5年，规则会优先从高到低匹配，先判断是否超过5年，如果没有超过则再判断是否超过2年，以此类推。</p>
        <a-button type="primary" @click="addRow" style="margin-top: 16px">
          新增
        </a-button>
        <a-table :data="rulesData" :columns="rulesColumns" :pagination="false" bordered>
          <template #number="{ record, rowIndex }">
            <a-input-number v-model.trim="record.number" allow-clear="false" />
          </template>
          <template #scale="{ record, rowIndex }">
            <a-select v-model.trim="record.scale">
              <a-option v-for="item of scales" :value="item.value" :label="item.label" />
            </a-select>
          </template>
          <template #ratio="{ record, rowIndex }">
            <a-row>
              <a-col :span="20">
                <a-input v-model.trim="record.ratio" >
                  <template #prepend>
                    0.00 ~ 1.00 之间
                  </template>
                </a-input>
              </a-col>
              <a-col :span="1">
              </a-col>
              <a-col :span="2">
                <a-button @click="deleteRow(rowIndex)">
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-col>
            </a-row>
          </template>

        </a-table>
      </a-space>
      <br />
    </fieldset>
  </a-modal>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getDepreciationRules, addDepreciationRules, updateDepreciationRules } from '@/apis/asset/depreciation/rules'
  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'

  const emit = defineEmits < {
  (e: 'save-success'): void
}> ()

  const { width } = useWindowSize()

  const dataId = ref('')
  const visible = ref(false)
  const isUpdate = computed(() => !!dataId.value)
  const title = computed(() => (isUpdate.value ? '修改折旧规则' : '新增折旧规则'))
  const formRef = ref < InstanceType < typeof GiForm >> ()

  // 规则
  const rulesData = ref < TableData[] > ([]);

  const [form, resetForm] = useResetReactive({
    // todo 待补充
  })

  const columns: ColumnItem[] = reactive([
    {
      label: '名称',
      field: 'name',
      type: 'input',
      span: 24,
      required: true,
      props: {
        maxLength: 20
      },
    },
    {
      label: '描述',
      field: 'description',
      type: 'textarea',
      props: {
        maxLength: 250
      },
      span: 24,
    },
  ])

  const rulesColumns = [
    {
      title: '周期',
      dataIndex: 'number',
      slotName: 'number'
    },
    {
      title: '尺度',
      dataIndex: 'scale',
      slotName: 'scale'
    },
    {
      title: '比例',
      dataIndex: 'ratio',
      slotName: 'ratio'
    }
  ]

  // scale
  const scales = [
    {
      value: 'day',
      label: '天',
    },
    {
      value: 'month',
      label: '月',
    },
    {
      value: 'year',
      label: '年',
    }
  ]

  // 重置
  const reset = () => {
    rulesData.value = [];
    formRef.value?.formRef?.resetFields()
    resetForm()
  }

  // 删除联系人
  const deleteRow = (index: number) => {
    rulesData.value.splice(index, 1);
  };

  // 添加
  const addRow = () => {
    const newRow: TableData = {
      number: '',
      scale: '',
      ratio: ''
    };
    rulesData.value.push(newRow);
  };

  // 保存
  const save = async () => {
    try {
      form.rules = JSON.stringify(rulesData.value)
      console.log(JSON.stringify(rulesData.value))
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
      if (isUpdate.value) {
        await updateDepreciationRules(form, dataId.value)
        Message.success('修改成功')
      } else {
        await addDepreciationRules(form)
        Message.success('新增成功')
      }
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }

  // 新增
  const onAdd = async () => {
    reset()
    dataId.value = ''
    visible.value = true
  }

  // 修改
  const onUpdate = async (id: string) => {
    reset()
    dataId.value = id
    const { data } = await getDepreciationRules(id)
    rulesData.value = data.rules ? JSON.parse(data.rules) : rulesData.value
    Object.assign(form, data)
    visible.value = true
  }

  defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss">
  fieldset {
    padding: 15px 15px 0 15px;
    margin-bottom: 15px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }

  fieldset legend {
    color: rgb(var(--gray-10));
    padding: 2px 5px 2px 5px;
    border: 1px solid var(--color-neutral-3);
    border-radius: 3px;
  }
</style>